<template>
  <el-dialog :title="dialogProps.title" :visible.sync="dialogProps.visible" width='650px' class='charEdit'  :fullscreen = 'Global.currentDevice'>
        <el-form :model="form" ref='form' :rules="rules"  :label-width="formLabelWidth"  :label-position='Global.dialog_label_Position'>
              <el-tabs  >
                    <el-tab-pane label="基本信息" name="first">基本信息</el-tab-pane>
              </el-tabs>
              <el-form-item label="名称"  prop="name" align='left'>
                    <el-input v-model.trim="form.name" placeholder='请输入角色名称 ' ></el-input>
              </el-form-item>
              <el-form-item label="描述"  prop='description' align='left'>
                    <el-input v-model.trim="form.description" placeholder='请输入角色描述'></el-input>
              </el-form-item>
        </el-form>
        <el-tabs >
              <el-tab-pane label="权限信息" name="second">权限信息</el-tab-pane>
        </el-tabs>
        <el-tree ref='tree'  
              :data="data"
              show-checkbox
              node-key="code"
              :default-checked-keys="[5]"
              :props="defaultProps"
              :default-expand-all='true'
              :check-on-click-node = 'true'
              :expand-on-click-node = 'false'
              :check-strictly = 'true'
              @node-click="(data,checked,node)=>nodeclick(data,checked,node)"
              @check="clickDeal"
              >
        </el-tree>
              
        
        <div slot="footer" class="dialog-footer">
              <el-button @click="dialogProps.visible = false">取 消</el-button>
              <el-button type="primary" @click="submit('form')">确 定</el-button>
        </div>
  </el-dialog>
</template>

<script charset="utf-8" type="text/javascript">
import { saveRole ,modifyRole} from '@/api/settings/index' 
export default {
  name: 'charEdit',
  props:{
    parentList: {
                    type: Array,
                    default:function(){
                          return [];
                    }
                }
  },
  data() {
    return {
      loading: false,
      //dialogo基本信息  显示隐藏状态  title 
      dialogProps: {
        visible: false,
        action: '',
        title: ''
      },
      

      //表单label向外marin
      formLabelWidth: '120px',
      //表单验证规则
      rules:{
        name:[
          { required:true ,message:'请输入名称'}
        ]
      },
      //tree 必须要设置的，为了展开下一级  
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      //tree  data 模拟数据
        // data: [
        //     {
        //           id: 1,
        //           label: '企业',
        //           children: [{id: 4,label: '查看企业列表',},
        //               {label:'查看企业详情'},
        //               {label:'新增企业'},
        //               {label:'编辑企业'},
        //               {label:'删除企业'},
        //               {label:'入会提审'},
        //               {label:'平台准入提审'},
        //               {label:'导出'},
        //           ]
        //     }, 
        //     {
        //         id: 2,
        //         label: '业务',
        //         children: [
        //                    {id: 5,label: '项目',children:[
        //                                           {label:'查看项目列表'},
        //                                           {label:'查看项目详情'},
        //                                           {label:'新增项目'},
        //                                           {label:'编辑项目'},
        //                                           {label:'删除项目'},
        //                                           {label:'提审项目'},
        //                                           {label:'挂牌'},
        //                                           {label:'导出'},
        //                                       ]
        //                    },
        //                    {id: 6,label: '产品',children:[
        //                                           {label:'查看产品列表'},
        //                                           {label:'查看产品详情'},
        //                                           {label:'新增产品'},
        //                                           {label:'编辑产品'},
        //                                           {label:'删除产品'},
        //                                           {label:'提审产品'},
        //                                           {label:'上线'},
        //                                           {label:'复制'},
        //                     ]},
        //                    {id: 6,label: '标的',children:[
        //                                           {label:'查看标的列表'},
        //                                           {label:'查看标的详情'},
        //                                           {label:'新增标的'},
        //                                           {label:'编辑标的'},
        //                                           {label:'删除标的'},
        //                                           {label:'提审标的'},
        //                                           {label:'导出投资人列表'},
        //                                           {label:'导出'},
        //                     ]},
        //                    {id: 6,label: '合同',children:[
        //                                           {label:'查看合同列表'},
        //                                           {label:'查看合同详情'},
        //                                           {label:'新建文件夹'},
        //                                           {label:'编辑合同'},
        //                                           {label:'删除合同'},
        //                                           {label:'上传'},
        //                                           {label:'重命名'},
        //                                           {label:'显示/隐藏'},
        //                                           {label:'下载'},
        //                     ]},
        //                    {label:'清算',children:[
        //                                           {label:'产品维度'},
        //                                           {label:'标的维度'},
        //                     ]}
        //         ]
        //     },
        //     {id: 3,label: '审批',children: [{id: 7,label: '查看审批列表'},
        //                                     {id: 8,label: '查看审批详情'},
        //                                     {id: 8,label: '发起'},
        //                                     {id: 8,label: '撤回'},
        //                                     {id: 8,label: '导出'}
        //                                   ]
        //     },
        //     {id: 3,label: '用户',children: [{id: 7,label: '查看用户组详情'},
        //                                     {id: 8,label: '添加用户组'},
        //                                     {id: 8,label: '编辑用户组'},
        //                                     {id: 8,label: '删除用户组'},
        //                                     {id: 7,label: '查看用户详情'},
        //                                     {id: 8,label: '添加用户'},
        //                                     {id: 8,label: '编辑用户'},
        //                                     {id: 8,label: '删除用户'},
        //                                     {id: 8,label: '停用/启用'},
        //                                     {id: 8,label: '导入'},
        //                                     {id: 8,label: '导出'}
        //                                   ]
        //     },
        //     {id: 3,label: '日志',children: [{id: 7,label: '登录日志'},
        //                                     {id: 8,label: '操作日志'},
        //                                   ]
        //     },
        //     {id: 3,label: '设置',children: [{id: 7,label: '查看角色列表'},
        //                                     {id: 8,label: '查看角色详情'},
        //                                     {id: 8,label: '添加角色'},
        //                                     {id: 8,label: '编辑角色'},
        //                                     {id: 8,label: '删除角色'},
        //                                     {id: 8,label: '导出角色'},
        //                                     {id: 7,label: '查看标签列表'},
        //                                     {id: 8,label: '查看标签详情'},
        //                                     {id: 8,label: '添加标签'},
        //                                     {id: 8,label: '编辑标签'},
        //                                     {id: 8,label: '删除标签'},
        //                                     {id: 8,label: '导出标签'},
        //                                   ]
        //     }
        // ],
      data:[],


      //绑定表单数据
      form: {
          name: '',
          description: '',
          menuCodes:[]
      },
      isEdit:false
    }
  },
  created(){
    // console.log(this.parentList)
  },
  methods: {
    //生成data树
    formTree(){
        let data = [];
        this.parentList.forEach((item)=>{
         
          if(item.id !=0 && item.parentId == 0){
              data.push({
                id:item.id,
                label:item.name,
                code:item.code,
                parentId:item.parentId
              })
          }
          
        })
        this.formNextTree(data)
        // this.$refs.tree.setCheckedKeys(this.form.menuCodes);//undefined
        this.$nextTick(() => {
            // console.log(this.$refs) //存在
            this.$refs.tree.setCheckedKeys(this.form.menuCodes);

            //将树的scrolltop 设置为0  是否可以用vue方法？不用控制节点的方案？
            document.querySelector('.el-tree').scrollTop = 0
        })
    },
    formNextTree(data){
        data.forEach((item)=>{
          let child= []
          this.parentList.forEach((it)=>{
            if(item.id == it.parentId){
                child.push({
                  id:it.id,
                  label:it.name,
                  code:it.code,
                  parentId:it.parentId
                })
            }
          })
          item.children=child
          if(child.length>0){
              this.formNextTree(child) //递归
          }
        })
        this.data=data
    },
    //提交
    submit(formName) {
       let that = this

      this.loading = true

      let choose = this.$refs.tree.getCheckedNodes().concat(this.$refs.tree.getHalfCheckedKeys())
      // console.log(choose)
      this.form.menuCodes = []//先全部值为空 ，再回填
      choose.forEach((item)=>{
         this.form.menuCodes.push(item.code)
      })

      //先验证表达
      this.$refs[formName].validate(valid => {
          //通过验证后
          if (valid) {
              if(this.form.menuCodes.length == 0){
                  return  this.$message({type:'error',message:'请选择至少一个角色权限！'})
              }
              if(this.isEdit == false){
                     saveRole(this.form)
                    .then(response => {
                      this.loading = false
                      this.dialogProps.visible = false
                      this.$message({type:'success',message:response.data.msg})
                      this.$emit('save-finished')
                    })
                    .catch(error => {
                      that.outputError(error)
                    })
              }
               else{
                  // console.log(this.form)
                     modifyRole(this.form)
                    .then(response => {
                      this.loading = false
                      this.dialogProps.visible = false
                      this.$message({type:'success',message:response.data.msg})
                      this.$emit('save-finished')
                    })
                    .catch(error => {
                      that.outputError(error)
                    })
               }

          } 
          else {
            return false;
          }
      });

      
    },
    //tree点击节点的回调函数  为了点击时在没有子节点的节点可以直接选中
    nodeclick(data,node,vuenode){
      // if(node.childNodes.length == 0){
      //   node.checked=!node.checked
      // }
    },
    clickDeal (currentObj, treeStatus) {
      // console.log(currentObj, treeStatus)
      // 用于：父子节点严格互不关联时，父节点勾选变化时通知子节点同步变化，实现单向关联。
      let selected = treeStatus.checkedKeys.indexOf(currentObj.code) // -1未选中
      // 选中
      if (selected !== -1) {
        // 子节点只要被选中父节点就被选中
        this.selectedParent(currentObj)
        // 统一处理子节点为相同的勾选状态
        this.uniteChildSame(currentObj, true)
      } else {
        // 未选中 处理子节点全部未选中
        if (currentObj.children.length !== 0) {
          this.uniteChildSame(currentObj, false)
        }
      }
    },
    // 统一处理子节点为相同的勾选状态
    uniteChildSame (treeList, isSelected) {
      // console.log(treeList)
      this.$refs.tree.setChecked(treeList.code, isSelected)
      if(treeList.children.length){
          for (let i = 0; i < treeList.children.length; i++) {
            this.uniteChildSame(treeList.children[i], isSelected)
          }
      }
      
    },
    // 统一处理父节点为选中
    selectedParent (currentObj) {
      let currentNode = this.$refs.tree.getNode(currentObj)
      if (currentNode.parent.key !== undefined) {
        this.$refs.tree.setChecked(currentNode.parent, true)
        this.selectedParent(currentNode.parent)
      }
    },

  },
  mounted: function() {

    this.$nextTick(() => {
      // this.formTree()
      this.$on('openEditDialog', function(data) {
        this.isEdit=true
        this.formTree()

        // console.log(this.$refs)
        // this.form=data
        let proxy = new Proxy(data, {
          get: function(target, property) {
            if(property == 'code' || property == 'description'  || property == 'name' || property == 'menuCodes')
            return target[property];
          }
        });
        this.form = proxy
        
        this.dialogProps.action = 'edit'
        this.dialogProps.title = '编辑角色'
        this.dialogProps.visible = true
      })
      this.$on('openAddDialog', function() {
        this.isEdit=false
        this.formTree()

        //设置form  为原始值
        this.form = {
          name: '',
          description: '',
          menuCodes:[]
        }
        //设置form表单验证  为原始值
        this.resetForm('form')

        this.dialogProps.action = 'add'
        this.dialogProps.title = '新增角色'
        this.dialogProps.visible = true
      })
    })
  },
  components:{
    
  }
}
</script>

<style  scoped>
.el-tree{height: 300px;overflow-y: auto;}
.el-input{max-width:350px;}
</style>


